import 'package:flutter/material.dart';
import 'package:flutter_baselib/flutter_baselib.dart';
import 'package:baselib_demo/common/net/http_urls.dart';
import 'package:baselib_demo/common/router/navigator_utils.dart';
import 'package:baselib_demo/module/login/bean/login_result_bean.dart';

///@date:  2021/3/1 11:57
///@author:  lixu
///@description: 登录ViewModel
class LoginViewModel extends BaseCommonViewModel {
  ///登录响应对象
  LoginResultBean? _loginResultBean;

  CancelToken? loginCancelToken;

  LoginResultBean? get loginResultBean => _loginResultBean;

  LoginViewModel() {}

  @override
  String getTag() {
    return 'LoginViewModel';
  }

  ///登录：http请求返回单个对象
  Future onLogin(BuildContext context, {bool isCancelableDialog = true}) async {
    Map<String, dynamic> map = {
      'account': '15015001500',
      'pass': '123qwe',
      'appType': 'PATIENT',
      'device': 'ANDROID',
      'push': '13065ffa4e22e63efd2',
    };

    loginCancelToken = CancelToken();

    Options option = Options();
    option.method = XApi.methodGet;

    await api.request<LoginResultBean>(
      HttpUrls.loginUrl,
      params: map,
      //优先级最高
      method: XApi.methodPost,
      //针对当前请求的配置选项，优先级次高
      option: option,
      cancelToken: loginCancelToken,
      //请求前检测网络连接是否正常，如果连接异常，直接返回错误
      isCheckNetwork: true,
      //显示加载dialog
      isShowLoading: true,
      //加载dialog显示的提示文本
      loadingText: '正在登录...',
      //请求失败时显示toast提示
      isShowFailToast: true,
      //TODO 请求过程中可以关闭加载弹窗（请求过程中关闭dialog时自动取消请求）
      isCancelableDialog: isCancelableDialog,
      onSuccess: (LoginResultBean? bean) {
        _loginResultBean = bean;
        ToastUtils.show('登录成功');
      },
      onError: (HttpErrorBean errorBean) {
        _loginResultBean = null;
        LogUtils.e(getTag(), '登录失败');
      },
      onComplete: () {
        LogUtils.i(getTag(), '登录完成');
      },
    );

    if (_loginResultBean != null) {
      NavigatorUtils.toHome(context);
    }
  }

  ///登录前请求必要的权限
  Future<bool> _loginBeforeRequestPermission() async {
    //TODO 文案或交互要修改
    bool isDefine = await PermissionUtils.requestPermission(Permission.storage);
    if (!isDefine) {
      ToastUtils.show('请开启存储权限,否则应用无法使用', isShowLong: true);
    }
    return isDefine;
  }

  @override
  void dispose() {
    super.dispose();
  }
}
